﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using Sprout.Schedule.Web.Exceptions;
using Sprout.Schedule.Web.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace Sprout.Schedule.Web.Utils
{
    public class ModelStateHelper
    {
        /// <summary>
        /// 获取参数验证异常返回值
        /// </summary>
        /// <param name="modelState"></param>
        /// <returns></returns>
        public static ResponseResult GetModelStateResult(ModelStateDictionary modelState)
        {
            if (modelState.IsValid)
            {
                return null;
            }
            var result = new ResponseResult
            {
                StatusCode = StatusCodeEnum.ValidateError,
                Message = "参数验证失败!"
            };
            var errorMessage = new Dictionary<string, string>();
            foreach (var key in modelState.Keys)
            {
                if (modelState[key].Errors.Count > 0)
                {
                    errorMessage.Add(key, modelState[key].Errors[0].ErrorMessage);
                }
            }
            result.Data = errorMessage;
            return result;
        }
    }
}
